const fs = require("fs");
const path = require("path");
const http = require("http");
const https = require("https");
const url = require("url");
const FormData = require("form-data");
const buffer = require("buffer");
const randomstring = require("randomstring");
const rp = require("request-promise-native");
const B64 = require("b64");
const stream = require("stream");
const CombinedStream = require("combined-stream");
const String2Stream = require("string-to-stream");
const getStream = require("get-stream");

const upload_url = "http://kefu.vivo.com.cn/robot-vivo/upload.action?userId=null&sessionId=null";
const parsed = url.parse(upload_url);

/**
 * 
 * @param {String} full_path 
 */
function uploadSingle(full_path) {
    return new Promise(async (resolve, reject) => {
        let file_stream = fs.createReadStream(full_path);
        let ext_name = path.extname(full_path);
        ext_name = ext_name ? ext_name.replace(".", "") : "bin";

        let form = new FormData;
        form.append("file", file_stream, {
            filename: `${randomstring.generate(5)}.${ext_name}`
        })
        let headers = {
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36",
            "Referer": "http://kefu.vivo.com.cn/robot-vivo/pcChat.html",
            'X-Requested-With': 'XMLHttpRequest'
        }
        let request = https.request({
            method: "POST",
            host: parsed.host,
            path: parsed.path,
            headers: {
                ...form.getHeaders(),
                ...headers
            }
        });
        form.pipe(request);
        request.on("response", (resp) => {
            let buf = new buffer.Buffer("");
            resp.on("data", chunk => {
                buf += chunk;
            })
            resp.on("end", $ => {
                try {
                    let obj = JSON.parse(buf);
                    let file_url = obj['fileUrl'];
                    console.log(path.basename(full_path));
                    console.log(file_url);
                    resolve(file_url);
                } catch (e) {
                    reject(e);
                }
            })
            // resp.pipe(process.stdout);
        });
        request.on("error", err => reject(err));
    })
}
/**
 * @param {Number} x
 * @param {String} full_path 
 */
function uploadSingleForXTime(x, full_path) {
    let g = (function* () {
        for (let i = 1; i <= x; i++) {
            yield uploadSingle(full_path);
        }
    })();
    let it = g.next();
    return new Promise((resolve, reject) => {
        (function bootstrap() {
            if (it.done) {
                reject(x + "times failed");
            } else {
                it.value.then(() => {
                    resolve();
                }).catch(e => {
                    it = g.next();
                    bootstrap();
                })
            }
        })();
    })
}




if (!module.parent) {
    uploadSingle(path.join(__dirname, "../33MB.gif"));
}

module.exports = {
    uploadSingleForXTime: uploadSingleForXTime
}